package com.hakim.wfb.admin.task;

import com.hkfs.fundamental.common.utils.ExecutorUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StopWatch;

import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutorService;


/**
 * <p>任务基类</p>
 *
 * @Author dzr
 * @Date 2016/04/30
 */
public abstract class BaseTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(BaseTask.class);

    public abstract boolean isTaskenable();

    protected String taskName;

    @PostConstruct
    public void init() {
        this.taskName = this.getClass().getName();
        if (getTaskName() != null || !"".equals(getTaskName())) {
            this.taskName = this.getTaskName();
        }
        LOGGER.info("任务[" + taskName + "]初始化成功……");
    }

    /**
     * 执行方法
     */
    public void execute() {
        if (!isTaskenable()) {
            return;
        }
        ExecutorService executorService = ExecutorUtils.getCachedThreadPool("DJDTask");
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                LOGGER.info("[" + taskName + "]开始执行……");
                StopWatch stopWatch = new StopWatch();
                stopWatch.start(taskName);
                try {
                    doTask();
                } catch (Exception e) {
                    LOGGER.error("[" + taskName + "]执行失败", e);
                } finally {
                    stopWatch.stop();
                    LOGGER.info("[" + taskName + "]执行结束……,耗时:" + stopWatch.getTotalTimeMillis() + "(毫秒)");
                }
            }
        });
    }

    /**
     * 业务方法
     */
    public abstract void doTask();

    /**
     * 获取当前任务的名称，由开发人员自己定义
     *
     * @return
     */
    public abstract String getTaskName();

}
